package com.abe.gcore.base.mvp.rxandroid;

import com.abe.gcore.base.BaseTResultEntity;
import com.abe.gcore.base.mvp.IBasePresenter;
import com.abe.gcore.base.mvp.IView;
import com.abe.gcore.utils.CoreNormalUtils;

import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

public abstract class IRxBasePresenter<V extends IView> extends IBasePresenter<V> implements IRxPresenter {

    //将所有正在处理的Subscription都添加到CompositeSubscription中。统一退出的时候注销观察
    private CompositeDisposable mCompositeDisposable;

    /**
     * 将Disposable添加
     *
     * @param subscription subscription
     */
    @Override
    public void addDisposable(Disposable subscription) {
        //csb 如果解绑了的话添加 sb 需要新的实例否则绑定时无效的
        if (mCompositeDisposable == null || mCompositeDisposable.isDisposed()) {
            mCompositeDisposable = new CompositeDisposable();
        }
        mCompositeDisposable.add(subscription);
    }

    /**
     * 在界面退出等需要解绑观察者的情况下调用此方法统一解绑，防止Rx造成的内存泄漏
     */
    @Override
    public void unDisposable() {
        if (mCompositeDisposable != null) {
            mCompositeDisposable.dispose();
        }
    }

    ////////////////////////////////////////////////////////////////////////////////////////////////
    protected Consumer<Disposable> DisposableConsumer() {
        return new Consumer<Disposable>() {
            @Override
            public void accept(@NonNull Disposable disposable) throws Exception {
                //请求加入管理
                addDisposable(disposable);
            }
        };
    }

    protected void checkT(BaseTResultEntity resultEntity) {
        if (resultEntity.getErrorCode() < 0) {
            CoreNormalUtils.showShortToastR(resultEntity.getErrorMsg());
        }
    }

    protected abstract void onCheckSuccess(Object obj, String method);

    protected void checkData(Object obj, String method, String type) {
        if (isViewAttached()) {
            if (obj != null) {
                onCheckSuccess(obj, method);
                getView().onFinish(type);
            } else {
                showViewDataNullError();
            }
        } else {
            showViewAttachedError();
        }
    }

    protected Consumer<Throwable> ThrowableConsumer(final String type) {
        return new Consumer<Throwable>() {
            @Override
            public void accept(@NonNull Throwable throwable) throws Exception {
                if (isViewAttached()) {
                    w(throwable.getMessage());
                    getView().showMessage(0, throwable.getMessage());
                    getView().onFaild(type);
                    getView().onFinish(type);
                } else {
                    showViewAttachedError();
                }
            }
        };
    }
}
